package com.example.server.handle;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SessionCache {

    private final static Map<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();

    public static void add(WebSocketSession session) {
        SESSION_MAP.putIfAbsent(session.getId(), session);
    }

    public static void remove(String sessionId) {
        SESSION_MAP.remove(sessionId);
    }

    public static Set<String> getAll() {
        return SESSION_MAP.keySet();
    }

    public static WebSocketSession get(String sessionId) {
        return SESSION_MAP.get(sessionId);
    }

    public static void sendMessage(String sessionId, String message) {
        if (null != sessionId) {
            WebSocketSession session = SESSION_MAP.get(sessionId);
            if (null != session) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    log.error("发送消息异常，sessionId:{}", session.getId(), e);
                }
            }
        } else {
            for (Map.Entry<String, WebSocketSession> entry : SESSION_MAP.entrySet()) {
                try {
                    entry.getValue().sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    log.error("发送消息异常，sessionId:{}", entry.getKey(), e);
                }
            }
        }
    }
}
